package com.feib.stms.action;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.DontBind;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.Validate;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import com.feib.stms.model.Group;
import com.feib.stms.model.LabelValue;
import com.feib.stms.model.Securities;
import com.feib.stms.model.TempUser;
import com.feib.stms.model.User;
import com.feib.stms.pagination.PaginatedList;
import com.feib.stms.service.GroupService;
import com.feib.stms.service.SecuritiesService;
import com.feib.stms.service.TempUserService;
import com.feib.stms.service.UserService;
import com.feib.stms.util.UserUtil;


/**
 * @title (#)Soez9015ActionBean.java<br>
 * @description 使用者資料維護放行 <br>
 * @author Lion Gao<br>
 * @version 1.0.0 2012/06/08
 * @copyright Far Eastern International Bank Copyright (c) 2012<br>
 * @2012/06/08 create by Lion Gao<br>
 *
 */
public class Stms9015ActionBean extends BaseActionBean{

	/**
	 * 
	 */
	private static final long serialVersionUID = -7973178904013567097L;

	/**
	 * 使用者資料放行畫面
	 */
	private static final String DEFAULT_JSP = "/WEB-INF/views/stms9015/stms9015.jsp";

	/**
	 * 使用者資料明細畫面
	 */
	private static final String DETAIL_JSP = "/WEB-INF/views/stms9015/stms9015Detail.jsp";

	/*畫面sortHeader傳回來的值*/
	private static List<String> SORT_KEYS = new ArrayList<String>();
	static{
		SORT_KEYS.add("userId".toLowerCase());
		SORT_KEYS.add("userName".toLowerCase());
		SORT_KEYS.add("userPhoneNo".toLowerCase());
		SORT_KEYS.add("userEmail".toLowerCase());
	}

	/*使用SORT_KEYS作key值取得對應的資料庫欄位名稱*/
	private static Map<String,String> SORT_FIELD =  new HashMap<String, String>();
	static{
		SORT_FIELD.put("userId".toLowerCase(), "USER_ID");
		SORT_FIELD.put("userName".toLowerCase(), "USER_NAME");
		SORT_FIELD.put("userPhoneNo".toLowerCase(), "USER_PHONE_NO");
		SORT_FIELD.put("userEmail".toLowerCase(), "USER_EMAIL");
	}

	/** 
	 * 查詢條件-使用者ID
	 */
	private String qryTempUserIdForm;

	/** 
	 * 查詢條件-姓名
	 */
	private String qryTempUserNameForm;

	/**
	 * 查詢結果
	 */
	private PaginatedList<TempUser> queryResult;

	@Validate( required=true, on={"doUpdate"})
	private Long qryTempUserPk;

	/**
	 * 用於修改綁定 
	 */
	private TempUser editTempUser;

	/**
	 * 放行處理結果
	 */
	private String message;

	/**
	 * 使用者密碼
	 */
	private String password;

	/**
	 * 可處理券商資料列表 --獲取分公司
	 */
	private Collection<LabelValue> dealSecuritiesNos;

	/**
	 * 可處理券商資料-綁定
	 */
	private List<String> qryDealSecuritiesNos;

	/**
	 * 所屬分公司列表
	 */
	private List<Securities> securitiesOptionList;

	/**
	 * 用於顯示APP_USER中資料，在修改時候用於畫面對比顯示
	 */
	private User showEditUser;

	/**
	 * 用於顯示APP_USER中資料，在修改時候用於畫面對比顯示 --顯示可處理資料
	 */
	private List<LabelValue> showDealSecuritiesNos;

	@SpringBean("tempUserService")
	private TempUserService tempUserService;

	@SpringBean("securitiesService")
	private SecuritiesService securitiesService;

	@SpringBean("userService")
	private UserService userService;

	@SpringBean("groupService")
	private GroupService groupService;

	@DontBind
	@DefaultHandler
	public Resolution doDefault() { 
		logger.debug("Enter doDefault mehtod.");
		return this.doQuery();
	}

	/**
	 * 查詢
	 * @return
	 */
	public Resolution doQuery()
	{
		logger.debug("Enter doQuery mehtod.");
		try{
			/* 設定換頁、排序等條件*/
			String sortCriterion = "userId";
			int sortDirection = 1;
			PaginatedList<TempUser> qryCondition = new PaginatedList<TempUser>();
			if (null != queryResult)
			{	
				//畫面傳入的排序字段
				sortCriterion = queryResult.getSortCriterion();
				sortDirection = queryResult.getSortDirection();
				//分頁
				qryCondition.setPageNumber(queryResult.getPageNumber());
				qryCondition.setPageSize(queryResult.getPageSize());
				//將畫面傳入的排序字段轉換為資料庫對應的字段
				String StringSortCriterion = SORT_FIELD.get(sortCriterion.toLowerCase());
				//設置排序
				qryCondition.setSortCriterion(StringSortCriterion);
				qryCondition.setSortDirection(sortDirection);
				logger.debug(" qryCondition:sortCriterion={}  sortDirection={} ", new Object[]{qryCondition.getSortCriterion(), qryCondition.getSortDirection()});

			}
			/*沒有設定排序就以第一欄作排序條件*/
			if (null == queryResult || StringUtils.isEmpty(queryResult.getSortCriterion()) || !SORT_KEYS.contains(queryResult.getSortCriterion().toLowerCase()))
			{
				qryCondition.setSortCriterion(SORT_FIELD.get(SORT_KEYS.get(0)));
			}

			/* 設定查詢條件*/
			TempUser qryTempUser = new TempUser();
			qryTempUser.setUserId(qryTempUserIdForm);
			qryTempUser.setUserName(qryTempUserNameForm);
			//調用service,到資料庫撈取DB
			this.queryResult = tempUserService.queryByTempUser(qryTempUser, qryCondition);

			if (null == this.queryResult)
				this.queryResult = qryCondition;

			queryResult.setSortCriterion(sortCriterion);
			queryResult.setSortDirection(sortDirection);

//			if (CollectionUtils.isEmpty(this.queryResult.getPaginatedList()))
//			this.message = "查無資料！";
			return new ForwardResolution(DEFAULT_JSP); 
		}catch(Exception e){
			logger.debug("查詢出錯(doQuery)",e);
		}
		return new ForwardResolution(DEFAULT_JSP); 
	}

	/**
	 * 檢視使用者
	 * @return
	 */
	public Resolution doUpdate()
	{
		logger.debug("Enter doUpdate mehtod.");
		try {
			this.editTempUser = this.tempUserService.findByTempUerPk(qryTempUserPk);
			if(editTempUser == null){
				message = "待放行使用者資料不存在!";
				return new ForwardResolution(DEFAULT_JSP); 
			}
			if(TempUser.USER_RECORD_SATAUS_UPDATE_MODE.equals(editTempUser.getRecordStatus())){//修改時候，才對比
				//查詢出修改對比資料
				this.showEditUser = this.userService.findByUerId(editTempUser.getUserId(), editTempUser.getGroup().getGroupPk());
				//處理畫面顯示可處理資料比對資料
				String tempDealSecuritiesNos = showEditUser == null?null:showEditUser.getDealSecuritiesNos();
				if(!StringUtils.isEmpty(tempDealSecuritiesNos)){
					String[] dealSnos = tempDealSecuritiesNos.split(",");
					List<String> tempDealSecuritiesNo = new ArrayList<String>();
					if(StringUtils.isNotEmpty(tempDealSecuritiesNos)){
						for(String securitiesNo:dealSnos){
							if(null != securitiesNo){
								tempDealSecuritiesNo.add(securitiesNo);
							}
						}
					}
					List<Securities> tempBranch = this.securitiesService.findForSecuritiesListBySecuritiesNos(tempDealSecuritiesNo);
					if(null != tempBranch && tempBranch.size()>0){
						this.showDealSecuritiesNos = new ArrayList<LabelValue>();
						//分公司查詢結果長度
						int j = tempBranch.size();
						for(int i = 0; i < j; i++){
							LabelValue labelValue = new LabelValue();
							labelValue.setLabel(tempBranch.get(i).getSecuritiesName());
							labelValue.setValue(tempBranch.get(i).getSecuritiesPk().toString());
							this.showDealSecuritiesNos.add(labelValue);
						}
					}
				}
			}
		}
		catch (Exception e) {
			logger.error("使用者資料放行查詢錯誤(doUpdate):", e);
			message = "系統出現異常!";
			return this.doQuery();
		}
		return new ForwardResolution(DETAIL_JSP); 
	}

	/**
	 * 放行
	 * @return
	 */
	public Resolution doPass(){
		logger.debug("Enter doPass mehtod.");
		User loginUser = UserUtil.getUser();
		try{
			if(TempUser.USER_RECORD_SATAUS_ADD_MODE.equals(this.editTempUser.getRecordStatus())){//記錄狀態為-新增
				/*
				 * 放行，做兩步操作
				 * 1.更新TempUser表資料欄位
				 * 2.更新User表資料欄位
				 */
				//1.更新User表
				//從db中檢索待放行資料
				TempUser tempUser = this.tempUserService.findByTempUerPk(this.editTempUser.getTempUserPk());				
				User user = tempUser.getUser();
				user.setCreatedBy(tempUser.getCreatedBy());
				user.setCreatedDate(tempUser.getCreatedDate());
				int returnCount = this.userService.saveUser(user);
				// 2.更新TempUser
				tempUser.setConfirmDate(new Date());//放行日期
				tempUser.setConfirmStatus(TempUser.USER_STATUS_CONFIRM_Y);//放行成功
				tempUser.setConfirmUserPk(loginUser.getUserPk());//放行者
				tempUser.setUpdatedBy(loginUser.getGroup().getGroupNo() + "_" + loginUser.getUserId());
				tempUser.setUpdatedDate(new Date());
				int returnCount2 = 0;
				if(returnCount > 0){
					returnCount2 = this.tempUserService.updateTempUser(tempUser);
				}
				this.message = returnCount > 0 && returnCount2 > 0?"使用者資料新增放行完成!":"處理失敗!";
				return this.doQuery();
			}else if(TempUser.USER_RECORD_SATAUS_UPDATE_MODE.equals(this.editTempUser.getRecordStatus())){//記錄狀態為-修改
				//1.更新User表
				//從db中檢索待放行資料
				TempUser tempUser = this.tempUserService.findByTempUerPk(this.editTempUser.getTempUserPk());
				User user = tempUser.getUser();				
				user.setUpdatedBy(tempUser.getUpdatedBy() == null ? tempUser.getCreatedBy() : tempUser.getUpdatedBy());
				user.setUpdatedDate(tempUser.getUpdatedDate() == null ? tempUser.getCreatedDate() : tempUser.getUpdatedDate());
				int returnCount = this.userService.updateUser(user);
				// 2.更新TempUser
				tempUser.setConfirmDate(new Date());//放行日期
				tempUser.setConfirmStatus(TempUser.USER_STATUS_CONFIRM_Y);//放行成功
				tempUser.setConfirmUserPk(loginUser.getUserPk());//放行者
				tempUser.setUpdatedBy(loginUser.getGroup().getGroupNo() + "_" + loginUser.getUserId());
				tempUser.setUpdatedDate(new Date());
				int returnCount2 = 0;
				if(returnCount > 0){
					returnCount2 =  this.tempUserService.updateTempUser(tempUser); 
				}
				this.message = returnCount > 0 && returnCount2 > 0?"使用者資料異動放行完成!":"處理失敗!";
				return this.doQuery();
			} 
		}catch(Exception e){
			logger.debug("處理失敗(doPass)",e);
			this.message = "處理失敗!";
			return this.doQuery(); 
		}
		return this.doQuery();
	}

	/**
	 * 退件
	 * @return
	 */
	public Resolution doBack(){
		logger.debug("Enter doBack mehtod.");
		User loginUser = UserUtil.getUser();
		try{
			//從db中檢索待放行資料
			TempUser tempUser = this.tempUserService.findByTempUerPk(this.editTempUser.getTempUserPk());
			//更新TempUser
			tempUser.setConfirmDate(new Date());//放行日期
			tempUser.setConfirmStatus(TempUser.USER_STATUS_CONFIRM_N);//退回
			tempUser.setConfirmUserPk(loginUser.getUserPk());//放行者
			tempUser.setUpdatedBy(loginUser.getGroup().getGroupNo() + "_" + loginUser.getUserId());
			tempUser.setUpdatedDate(new Date());
			this.tempUserService.updateTempUser(tempUser);
			if(TempUser.USER_RECORD_SATAUS_ADD_MODE.equals(this.editTempUser.getRecordStatus())){//記錄狀態為-新增				
				this.message = "使用者資料新增退件完成!";
			}else if(TempUser.USER_RECORD_SATAUS_UPDATE_MODE.equals(this.editTempUser.getRecordStatus())){//記錄狀態為-修改
				this.message = "使用者資料異動退件完成!";
			}			 
			return this.doQuery(); 

		}catch(Exception e){
			logger.debug("處理失敗(doBack)",e);
			this.message = "處理失敗!";
			return this.doQuery();
		}
	}

	/**
	 * 取消
	 * @return
	 */
	public Resolution doCancel()
	{
		logger.debug("Enter doCancel mehtod.");
		return doQuery();
	}

	/**
	 * @return dealSecuritiesNos
	 */
	public Collection<LabelValue> getDealSecuritiesNos() {
		/* 是否為銀行群組 */
		boolean isBankGroup = UserUtil.isBankGroup();
		/* 分公司查詢結果 */
		List<Securities> tempBranch = new ArrayList<Securities>();
		/* 如果不是銀行群組，則獲取登陸者當前帳號可處理券商的資料 */
		if(!isBankGroup){
			//獲取當前登錄用戶
			User user = UserUtil.getUser();
			//取得當前登錄用戶的可處理券商資料
			String userGroupPk = user.getGroup().getGroupPk().toString();
			//取得當前選擇處理券商的資料
			List<String> tempUserGroupPk = new ArrayList<String>();
			tempUserGroupPk.add(userGroupPk);
			/* 調用查詢 */
			try {
				tempBranch = securitiesService.findForSecuritiesListByGroupPks(tempUserGroupPk);
			} catch (Exception e) {
				tempBranch = null;
				logger.debug("Error in getDealSecuritiesNos() method !" + e);
			}
		}
		/* 如果是銀行群組，則可以查詢所有分公司的資料 */
		else{
			/* 調用查詢 */
			tempBranch = securitiesService.findForListBySecurities();
		}
		this.dealSecuritiesNos = new ArrayList<LabelValue>();
		if(!CollectionUtils.isEmpty(tempBranch) && tempBranch.size() > 0){
			for(Securities s:tempBranch){
				LabelValue labelValue = new LabelValue();
				labelValue.setLabel(s.getSecuritiesName());
				labelValue.setValue(s.getSecuritiesNo());
				dealSecuritiesNos.add(labelValue);
			}
		}
		//修改使用
		if(this.editTempUser != null){
			String strDealSecuritiesNos = this.editTempUser.getDealSecuritiesNos();//db中的可處理資料
			if(!StringUtils.isEmpty(strDealSecuritiesNos)){
				if(dealSecuritiesNos != null && dealSecuritiesNos.size() > 0){
					for(LabelValue l:dealSecuritiesNos){
						if(strDealSecuritiesNos.contains(l.getValue())){
							l.setChecked(true);
						}else{
							l.setChecked(false);
						}
					}
				}
			}
		}
		return dealSecuritiesNos;
	}

	/**
	 * @param dealSecuritiesNos 的設定的 dealSecuritiesNos
	 */
	public void setDealSecuritiesNos(Collection<LabelValue> dealSecuritiesNos) {
		this.dealSecuritiesNos = dealSecuritiesNos;
	}

	/**
	 * @return editTempUser
	 */
	public TempUser getEditTempUser() {
		return editTempUser;
	}

	/**
	 * @param editTempUser 的設定的 editTempUser
	 */
	public void setEditTempUser(TempUser editTempUser) {
		this.editTempUser = editTempUser;
	}

	/**
	 * @return message
	 */
	public String getMessage() {
		return message;
	}

	/**
	 * @param message 的設定的 message
	 */
	public void setMessage(String message) {
		this.message = message;
	}

	/**
	 * @return qryDealSecuritiesNos
	 */
	public List<String> getQryDealSecuritiesNos() {
		return qryDealSecuritiesNos;
	}

	/**
	 * @param qryDealSecuritiesNos 的設定的 qryDealSecuritiesNos
	 */
	public void setQryDealSecuritiesNos(List<String> qryDealSecuritiesNos) {
		this.qryDealSecuritiesNos = qryDealSecuritiesNos;
	}

	/**
	 * @return qryTempUserIdForm
	 */
	public String getQryTempUserIdForm() {
		return qryTempUserIdForm;
	}

	/**
	 * @param qryTempUserIdForm 的設定的 qryTempUserIdForm
	 */
	public void setQryTempUserIdForm(String qryTempUserIdForm) {
		this.qryTempUserIdForm = qryTempUserIdForm;
	}

	/**
	 * @return qryTempUserNameForm
	 */
	public String getQryTempUserNameForm() {
		return qryTempUserNameForm;
	}

	/**
	 * @param qryTempUserNameForm 的設定的 qryTempUserNameForm
	 */
	public void setQryTempUserNameForm(String qryTempUserNameForm) {
		this.qryTempUserNameForm = qryTempUserNameForm;
	}

	/**
	 * @return qryTempUserPk
	 */
	public Long getQryTempUserPk() {
		return qryTempUserPk;
	}

	/**
	 * @param qryTempUserPk 的設定的 qryTempUserPk
	 */
	public void setQryTempUserPk(Long qryTempUserPk) {
		this.qryTempUserPk = qryTempUserPk;
	}

	/**
	 * @return queryResult
	 */
	public PaginatedList<TempUser> getQueryResult() {
		return queryResult;
	}

	/**
	 * @param queryResult 的設定的 queryResult
	 */
	public void setQueryResult(PaginatedList<TempUser> queryResult) {
		this.queryResult = queryResult;
	}

	/**
	 * @return password
	 */
	public String getPassword() {
		return password;
	}

	/**
	 * @param password 的設定的 password
	 */
	public void setPassword(String password) {
		this.password = password;
	}

	/**
	 * @return showEditUser
	 */
	public User getShowEditUser() {
		return showEditUser;
	}

	/**
	 * @param showEditUser 的設定的 showEditUser
	 */
	public void setShowEditUser(User showEditUser) {
		this.showEditUser = showEditUser;
	}

	/**
	 * @return showDealSecuritiesNos
	 */
	public List<LabelValue> getShowDealSecuritiesNos() {
		return showDealSecuritiesNos;
	}

	/**
	 * @param showDealSecuritiesNos 的設定的 showDealSecuritiesNos
	 */
	public void setShowDealSecuritiesNos(List<LabelValue> showDealSecuritiesNos) {
		this.showDealSecuritiesNos = showDealSecuritiesNos;
	}

	/**
	 * @return securitiesOptionList
	 */
	public List<Securities> getSecuritiesOptionList() {
		/* 是否為銀行群組 */
		boolean isBankGroup = UserUtil.isBankGroup();
		/* 分公司查詢結果 */
		/* 如果不是銀行群組，則獲取登陸者當前帳號可處理券商的資料 */
		if(!isBankGroup){
			//獲取當前登錄用戶
			User user = UserUtil.getUser();
			//取得當前登錄用戶的可處理券商資料
			String userGroupPk = user.getGroup().getGroupPk().toString();
			//取得當前選擇處理券商的資料
			List<String> tempUserGroupPk = new ArrayList<String>();
			tempUserGroupPk.add(userGroupPk);
			/* 調用查詢 */
			try {
				securitiesOptionList = securitiesService.findForSecuritiesListByGroupPks(tempUserGroupPk);
			} catch (Exception e) {
				securitiesOptionList = null;
				logger.debug("Error in getSecuritiesOptionList() method !" + e);
			}
		}
		/* 如果是銀行群組，則可以查詢所有分公司的資料 */
		else{
			/* 調用查詢 */
			securitiesOptionList = securitiesService.findForListBySecurities();
		}
		return securitiesOptionList;
	}

	/**
	 * @param securitiesOptionList 的設定的 securitiesOptionList
	 */
	public void setSecuritiesOptionList(List<Securities> securitiesOptionList) {
		this.securitiesOptionList = securitiesOptionList;
	}

	/**
	 * @return selectedGroup
	 */
	public List<LabelValue> getSelectedGroup() {
		/* 查詢該角色權限下的用戶 */
		//如果資料清空
		List<LabelValue> selectedGroup = new ArrayList<LabelValue>();
		//是銀行群組--列出該角色下的所有用戶
		//保存查詢到得用戶
		List<Group> tempGroup;
		//去數據庫查詢資料
		try {
			tempGroup = groupService.findAllGroup();
		} catch (Exception e) {
			tempGroup = null;
		}
		//轉化資料為可用數據
		if(null != tempGroup && tempGroup.size() > 0){
			LabelValue labelValue;
			for(int i = 0 ; i < tempGroup.size() ; i++){
				labelValue = new LabelValue();
				//顯示為 群組No + 用戶ID  要不然頁面名稱容易混亂，不易區分
				labelValue.setLabel(tempGroup.get(i).getGroupName());
				labelValue.setValue(tempGroup.get(i).getGroupPk().toString());
				selectedGroup.add(labelValue);
			}
		}
		return selectedGroup;
	}

	/**
	 * @return isBankGroupUser
	 */
	public Boolean getIsBankGroupUser() {
		boolean tempIsBankGroupUser = UserUtil.isBankGroup();
		return tempIsBankGroupUser;
	}

	/*
	 * md5加密
	 */
	protected String toDecryptPasswordByMd5(String password){
		StringBuffer buf = new StringBuffer("");
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(password.getBytes());
			byte b[] = md.digest();
			int i;
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			return buf.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}
}
